package bd

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import oa.lla.cca.R
import bb.CD
import java.util.*

class CM:AppCompatActivity() {
    private var viewModule:FI? = null
    private var permissionList = Arrays.asList<String>(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_imagesource_layout)
        if (ActivityCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, permissionList.toTypedArray(),100)
        }else{
            initView()
        }
    }

    private fun initView() {
         viewModule = ViewModelProvider(this).get(FI::class.java)
         findViewById<ImageView>(R.id.back_left).setOnClickListener { finish() }
         viewModule?.getSDSources()
         supportFragmentManager.beginTransaction().add(R.id.source_content_layout,FD.newInstance()).commit()
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 100) {

            if (allPermissionsGranted()) {
                initView()
            } else {
                Toast.makeText(this, "没有相机授权与本地存储权限授权，无法使用！", Toast.LENGTH_SHORT).show()
                finish()
            }
        }


    }
    // 权限申请
    private fun allPermissionsGranted() = permissionList.all {
        ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && data!=null){
            val pageType = data.getStringExtra(CH.PAGE_TYPE)
            if (pageType.equals(CH.PAGE_IMAGE)){
                val fragment1 = supportFragmentManager.findFragmentByTag(
                    FD::class.java.simpleName
                )
                fragment1?.onActivityResult(requestCode, resultCode,data)
            }else{

            }
        }

    }

}